import axios from "axios";
import store from "./store";
import {
    jumpToLoginPage
} from "@/utils/common";
const namespace = "sso";
store.registerModule(namespace, {
    namespaced: true,

    state() {
        return {
            token: "",
        };
    },
});

const preload = async () => {
    const sp = new URLSearchParams(location.search);
    const token = sp.get("token");
    if (!token) return jumpToLoginPage();
    try {
        await getUserInfo(token);
        replaceState();
        return true;
    } catch (e) {
        jumpToLoginPage();
        return false;
    }
};

const getUserInfo = async (token) => {
    const {
        data
    } = await axios.get("/api/sso/wxUser/qrcodeStatus", {
        headers: {
            token: token,
        },
    });
    const {
        state
    } = store;
    state[namespace].token = data.token;
    return data;
};

// 去掉url中的参数信息
const replaceState = () => {
    const sp = new URLSearchParams(location.search);
    sp.delete("ticket");
    sp.delete("token");
    sp.delete("userId");
    sp.delete("type");
    const qs = sp.toString();
    const search = qs ? "?" + qs : "";
    const href = location.origin + location.pathname + search + location.hash;
    history.replaceState(null, document.title, href);
};

export default preload;